<template>
  <tm-app>
    <tm-navbar title="购物车" color="orange">
      <template v-slot:left>共{{ count + shopcount }}件</template>
    </tm-navbar>
    <div class="cart">
      <div class="cartlist">
        <div v-for="(items, index) in carInfoVoList" :key="index">
          <div style="padding: 20px">
            <tm-checkbox
              :modelValue="preferential"
              @change="handleChange1"
              :label="items.activityRule[1].ruleDesc"
            ></tm-checkbox>
          </div>
          <!-- <div v-for="activ in items.activityRule" :key="activ._id">
            <div v-for="item in items.cartInfoList" :key="item._id">
              <div :class="item.skuId == activ.id ? 'zai' : 'buzai'">
                {{ item.skuId == activ.id ? item.skuName : '' }}
              </div>
            </div>
          </div> -->

          <tm-divider align="left" color="blue"></tm-divider>
          <div v-for="item in items.cartInfoList" :key="item._id" class="cartitem">
            <div>
              <tm-checkbox
                color="green"
                :modelValue="item.isChecked ? true : false"
                @change="isChecked(item)"
              ></tm-checkbox>
            </div>
            <div style="display: flex; justify-content: space-between; width: 50%; align-items: center">
              <tm-image :preview="true" :width="80" :height="80" :src="item.imgUrl"></tm-image>
              <div style="width: 100%">
                {{ item.skuName }}
                <p>
                  <span style="color: red">￥</span>
                  {{ item.cartPrice }}
                </p>
              </div>
            </div>
            <div class="buttoms" style="display: flex; align-items: center" v-if="item.skuNum != 0">
              <tm-button :width="50" label="+" @click="skuSum(item, '1')"></tm-button>
              <div style="width: 100px; text-align: center">{{ item.skuNum }}</div>
              <tm-button :width="50" label="-" @click="skuSum(item, '-1')"></tm-button>
            </div>
            <div v-else>
              <tm-button
                style="background-color: rgb(255, 141, 11)"
                type="primary"
                @click="skuSum(item, '1')"
                :width="190"
                :height="60"
                label="加入购物车"
              ></tm-button>
            </div>
          </div>
          <hr />
        </div>
        <tm-divider align="left" color="red"></tm-divider>
        <div v-for="item in shoplist" :key="item._id" class="cartitem">
          <div>
            <tm-checkbox
              color="green"
              :modelValue="item.skuId.isChecked ? true : false"
              @change="shopisChecked(item)"
            ></tm-checkbox>
          </div>
          <div style="display: flex; justify-content: space-between; width: 50%; align-items: center">
            <tm-image :preview="true" :width="80" :height="80" :src="item.skuId.imgUrl"></tm-image>
            <div style="width: 100%">
              {{ item.skuId.skuName }}
              <p>
                <span style="color: red">￥</span>
                {{ item.skuId.marketPrice }}
              </p>
            </div>
          </div>
          <div class="buttoms" style="display: flex; align-items: center" v-if="item.skuNum != 0">
            <tm-button :width="50" label="+" @click="shopskuSum(item, '1')"></tm-button>
            <div style="width: 100px; text-align: center">{{ item.skuNum }}</div>
            <tm-button :width="50" label="-" @click="shopskuSum(item, '-1')"></tm-button>
          </div>
          <div v-else>
            <tm-button
              style="background-color: rgb(255, 141, 11)"
              type="primary"
              @click="shopskuSum(item, '1')"
              label="加入购物车"
              :width="190"
              :height="60"
            ></tm-button>
          </div>
        </div>
      </div>
      <div
        style="
          width: 100%;
          height: 50px;
          background-color: #f5f5f5;
          position: fixed;
          bottom: 0;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 10px;
          background-color: rgb(254, 255, 253);
        "
      >
        <div>
          <p>
            <tm-checkbox :modelValue="cartInfoListchk" @change="handleChange" shape="circle"></tm-checkbox>
          </p>
        </div>
        <div>
          <div style="color: red; font-size: 20px">
            现价：￥{{ count + shopcount ? cartprice + shoprice - amount : 0 }}
          </div>
          <div style="color: hotpink; font-size: 12px">
            {{ count + shopcount ? `已优惠:￥${amount > 0 ? amount : 0}元,原价${cartprice + shoprice}` : '' }}
          </div>
        </div>

        <div style="">
          <tm-icon :font-size="50" name="tmicon-quan" @click="changPos"></tm-icon>
          <view>优惠券</view>
        </div>
        <button
          style="
            background-color: rgb(255, 141, 11);
            color: white;
            border-radius: 10%;
            height: 30px;
            width: 100px;
            line-height: 30px;
          "
          @click="goOrder"
        >
          立即结算
        </button>
      </div>
      <div>
        <tm-drawer ref="calendarView" placement="bottom" v-model:show="showWin">
          <view style="height: 100%">
            <div v-for="item in couponInfoList" :key="item._id">
              <Coupon :item="item" @apply="apply"></Coupon>
            </div>
          </view>
        </tm-drawer>
      </div>
      <div>
        <tm-modal
          color="white"
          okColor="red"
          cancelColor="red"
          okLinear="left"
          splitBtn
          @ok="finish"
          title="确定框"
          content="确定要删除吗"
          :hideCancel="true"
          v-model:show="showWin1"
        ></tm-modal>
      </div>
      <div>
        <tm-modal
          color="white"
          okColor="red"
          cancelColor="red"
          okLinear="left"
          splitBtn
          @ok="finish2"
          title="确定框"
          content="确定要删除吗"
          :hideCancel="true"
          v-model:show="showWin2"
        ></tm-modal>
      </div>
    </div>
  </tm-app>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import tmCheckbox from '@/tmui/components/tm-checkbox/tm-checkbox.vue'
import tmButton from '@/tmui/components/tm-button/tm-button.vue'
import tmImage from '@/tmui/components/tm-image/tm-image.vue'
import tmIcon from '@/tmui/components/tm-icon/tm-icon.vue'
import tmNavbar from '@/tmui/components/tm-navbar/tm-navbar.vue'
import tmDrawer from '@/tmui/components/tm-drawer/tm-drawer.vue'
import tmApp from '@/tmui/components/tm-app/tm-app.vue'
import tmModal from '@/tmui/components/tm-modal/tm-modal.vue'
import tmDivider from '@/tmui/components/tm-divider/tm-divider.vue'

import {
  cartgetapi,
  handleChangeapi,
  isCheckedapi,
  handleChange1api,
  skuSumapi,
  finishapi,
  shopskuSumapi,
  shopgetapi,
  finish2api,
  shopisCheckedapi,
} from '@/api'
import Coupon from '@/components/Coupon/coupon.vue'
// import Jia from './jia.vue'

const cartlist = ref<any>([]) // 使用泛型指定 ref 的类型
interface couponInfo {
  amount: number
  couponType: string
  endTime: string
  startTime: string
  rangeDesc: string
  rangeType: string
  couponStatus: boolean
  isOptimal: string
  isSelect: 1
  perLimit: string
  _id: string
}
const couponInfoList = ref<couponInfo[]>([]) // 优惠券列表
interface carInfoVo {
  cartPrice: number
  imgUrl: string
  isChecked: number
  isNewPerson: number
  skuId: number
  skuName: string
  skuNum: number
  skuType: number
  _id: string
}
const cartInfoList = ref<carInfoVo[]>([]) // 商品列表
interface activityCart {
  ruleDesc: string
}
const activityCartList = ref<activityCart[]>([]) // 活动列表

const carInfoVoList = ref<any>([]) //商品列表+活动列表
const showWin = ref<boolean>(false) //下弹框
const shoplist = ref<any>([]) //购物车

//总价
const cartInfoListchk = computed(() => {
  const chk: boolean = cartInfoList.value.every((item: any) => {
    return item.isChecked == 1
  })
  const chk1: boolean = shoplist.value.every((item: any) => {
    return item.skuId.isChecked == 1
  })
  return chk && chk1
})
const preferential = computed(() => {
  const chk = cartInfoList.value.every((item: any) => {
    return item.isChecked == 1
  })
  return chk
})
//dak
function changPos() {
  showWin.value = true
}
const goOrder = () => {
  uni.navigateTo({
    url: '/pages/order/index',
  })
}
interface Root {
  _id: string
  id: number
  keyword: string
  skuType: number
  isNewPerson: number
  categoryName: string
  imgUrl: string
  title: string
  price: number
  perLimit: number
  sale: number
  isChecked: number
  ruleList: any[]
  marketPrice: number
  categoryId: number
  __v: number
  skuName: string
  stock: number
}
interface objs {
  skuId: Root
  skuNum: number
  isChecked: number
}
//优惠卷使用

const CouponId = ref<number>() //优惠卷id
const amount = ref<number>(0) //减少金额
const apply = async (item: any): Promise<void> => {
  CouponId.value = item._id
  amount.value = item.amount

  cartget()
}
onMounted(() => {
  cartget(), shopget()
})
//选中后的价格
const cartprice = computed(() => {
  let price: number = 0
  cartInfoList.value.forEach((item: any) => {
    if (item.isChecked == 1) {
      price += item.cartPrice * item.skuNum
    }
  })

  return price
})
const shoprice = computed(() => {
  let price: number = 0
  shoplist.value.forEach((item: any) => {
    if (item.skuId.isChecked == 1) {
      price += item.skuId.marketPrice * item.skuNum
    }
  })

  return price
})

//选中商品的数量
const count = computed(() => {
  let num = 0
  cartInfoList.value.forEach((item: any) => {
    if (item.isChecked == 1) {
      num += item.skuNum
    }
  })
  return num
})
//选中商品的数量
const shopcount = computed(() => {
  let num = 0
  shoplist.value.forEach((item: objs) => {
    if (item.skuId.isChecked) {
      num += item.skuNum
    }
  })
  return num
})

// type BaseRequest<T, V> = (params?: T) => Promise<AxiosResponse<V>>
// T V泛型的约束
//T请求参数的类型 V响应的数据类型
//活动列表+优惠卷+活动
const cartget = async () => {
  let res = await cartgetapi()
  cartlist.value = res
  cartInfoList.value = cartlist.value.carInfoVoList[0].cartInfoList //购物车列表
  activityCartList.value = cartlist.value.carInfoVoList[0].activityRule //活动列表
  carInfoVoList.value = cartlist.value.carInfoVoList //商品列表+活动列表
  couponInfoList.value = cartlist.value.couponInfoList //优惠卷
  couponInfoList.value.filter((item: any) => {
    if (item.isSelect == 0) {
      CouponId.value = item._id
      amount.value = item.amount
    }
  })
}
//全选
const handleChange = async (isChecked: boolean): Promise<void> => {
  await handleChangeapi(isChecked)

  cartget()
  shopget()
}
const handleChange1 = async (isChecked: boolean): Promise<void> => {
  await handleChange1api(isChecked)

  cartget()
  shopget()
}

let cartitem = ref<number | string | undefined>()
let cartkey = ref<string | undefined>()
const showWin1 = ref<boolean>(false) //删除弹出框
const finish = async (): Promise<void> => {
  await finishapi(cartitem.value, cartkey.value)
  showWin1.value = false
  cartget()
}
//数量加减
const skuSum = async (item: objs, key: string): Promise<void> => {
  cartitem.value = item.skuId
  cartkey.value = key
  if (item.skuNum == 1 && key == '-1') {
    showWin1.value = true
  } else {
    await skuSumapi(item.skuId, key)
    shopget()
    cartget()
  }
}
// 案例
// import axios, { AxiosResponse } from 'axios'
// type BaseRequest<T, V> = (params?: T) => Promise<AxiosResponse<V>>
// interface GetTodoInfoParams {
//   id: number
// }
// export interface TodoInfo {
//   userId: number
//   id: number
//   title: string
//   completed: boolean
// }

// const getTodoInfo: BaseRequest<GetTodoInfoParams, TodoInfo> = () => {
//   return http.get(`/cart/cartList`)
// }
// getTodoInfo().then((res) => {
//   console.log(res)
// })
//是否选中
const isChecked = async (item: objs): Promise<void> => {
  if (item.isChecked == 1) {
    item.isChecked = 0
  } else {
    item.isChecked = 1
  }
  await isCheckedapi(item.skuId, item.isChecked)
  shopget()
  cartget()
}
interface shop {
  _id: string
  skuNum: number
  skuId: {
    _id: string
    imgUrl: string
    skuName: string
    skuType: number
    marketPrice: number
    isChecked: number
  }
}
//购物车获取
const shopget = async (): Promise<void> => {
  const res = await shopgetapi()
  shoplist.value = res
}

//购物车
const shopskuSum = async (item: shop, key: string) => {
  cartitem.value = item._id
  cartkey.value = key
  if (item.skuNum == 1 && key == '-1') {
    showWin2.value = true
  } else {
    await shopskuSumapi(item._id, key)
    cartget()
    shopget()
  }
}
//
const showWin2 = ref<boolean>(false) //删除弹出框
const finish2 = async (): Promise<void> => {
  await finish2api(cartitem.value, cartkey.value)
  showWin2.value = false
  shopget()
  cartget()
}

//购物车
const shopisChecked = async (item: shop) => {
  if (item.skuId.isChecked == 1) {
    item.skuId.isChecked = 0
  } else {
    item.skuId.isChecked = 1
  }
  await shopisCheckedapi(item.skuId._id, item.skuId.isChecked)
  shopget()
}
onMounted(() => {
  cartget()
  shopget()
})
</script>

<style lang="scss">
.cart {
  padding: 10px;
  font-size: 14px;
  height: 100vm;
  background-color: rgb(242, 244, 244);
  .cartlist {
    background-color: rgb(255, 255, 255);
    margin: 10px;
    .cartitem {
      border-radius: 10px;
      display: flex;
      justify-content: space-between;
      padding: 10px;
      border-bottom: 1px solid #ccc;
      align-items: center;
      height: 100px;
      .buttoms {
        display: flex;
        align-items: center;
        width: 30%;
        font-size: 20px;
        padding: 2px;
        background-color: rgb(242, 244, 244);
      }
    }
  }
}
.zai {
  display: block;
}
.buzai {
  display: none;
}
</style>
